<template>
<PublicPage page-name="商品库" :borderType="true" :showNav="true" :customBack="goBackFn">
  <view class="category">
    <!-- 搜索 -->
    <SearchInput placeholder="搜索商品名称" @searchFn="searchInputFn" />
    <view class="content">
      <!-- 侧边栏 -->
      <scroll-view class="goods-left" scroll-y="true" -webkit-overflow-scrolling="touch">
        <view
          class="li"
          v-for="(cate1, index) in categories"
          :key="index"
          :class="{ active: activeData.id == cate1.id }"
          @click.stop="changeIndex(cate1,index)"
        >
          {{ cate1.name }}
        </view>
      </scroll-view>
      <!-- 右侧主体 -->
      <scroll-view
      scroll-y="true"
      class="scroll-view-box"
      @scrolltolower="scrolltolowerFn"
      -webkit-overflow-scrolling="touch"
      >
        <ul class="goods-right" v-if="goodsList.length>0">
          <li class="goods-right-li" v-for="(goods, goodsIndex) in goodsList" :key="goodsIndex">
            <view class="goods-list" @click.stop="navigateTo({url: `/pagesB/goods/goodsDetails?shopWindowId=${goods.shopWindowId}`})">
              <view class="goods-list-img">
                <image class="list-img" mode="aspectFill" lazy-load="true" :src="goods.images[0].url"/>
                <!-- <span class="status_box" :class="{'status_box_at':goods.status==1}">{{goods.status | statusType}}</span> -->
              </view>
              <view style="color: rgba(0, 0, 0, 0.6)">
                <view class="goods-list-name"
                  >{{goods.goodsName}}</view
                >
                <view class="goods-list-inventory">库存：{{goods.quantity=='99999999'?'不限':goods.quantity}}</view>
                <view class="goods-list-price">
                  <span class="now themeFontColor" v-if="goods.minSalePrice==goods.maxSalePrice">￥{{goods.maxSalePrice}}</span>
                  <span class="now themeFontColor" v-else>￥{{goods.minSalePrice}}～{{goods.maxSalePrice}}</span>
                </view>
              </view>
            </view>
            <view class="goods-list-operation">
              <div class="goods-list-operation_l">
                <button class="btn_box" hover-class='hover' v-if="goods.isShopWindow==0" @click.stop="joinTheWindowFn(goods,1,goodsIndex)">移出小店</button>
                <button class="btn_box" hover-class='hover' v-else @click.stop="joinTheWindowFn(goods,0,goodsIndex)">加入小店</button>
              </div>
              <div class="goods-list-operation_r">
                <button class="btn_box" hover-class='hover' @click.stop="editGoodsFn(goods)">编辑</button>
                <button class="btn_box" hover-class='hover' @click.stop="deleteFn(goods,goodsIndex)">删除</button>
                <button class="btn_box" hover-class='hover' v-if="goods.status==1" @click.stop="operationFn(goods,goodsIndex)">下架</button>
                <button class="btn_box" hover-class='hover' v-else  @click.stop="operationFn(goods,goodsIndex)">上架</button>
              </div>
            </view>
          </li>
          <div class="no_more" v-if="queryGoodsType">没有更多了~</div>
        </ul>
        <div class="not_goods_box" v-else>
          <div class="not_msg_box">
            <img src="https://image.qqpyyds.com/mpAppImg/noneImg/search_default_img.png" alt="">
            <p>未找到相关商品</p>
          </div>
        </div>
      </scroll-view>
    </view>
    <!-- 底部固定 -->
    <button class="buttonStyleNone fixedBottomBtn" hover-class="hover" @click.stop="navigateTo({url:'/pagesA/libraryGoods/addProduct'})">发布商品</button>
  </view>
  <!-- 发布成功弹窗 -->
  <u-popup v-model="releaseType" mode="center" :zoom="false" border-radius="16" @click="closeReleaseFn">
    <view class="tips_popup_box">
      <view class="close_box" @click.stop="closeReleaseFn">
        <i class="iconfont icon-close fz-16" />
      </view>
      <view class="tips_popup_title1 linh-40 u-p-t-30">发布成功</view>
      <view class="tips_popup_text linh-40 u-p-b-30">恭喜你，商品发布成功</view>
      <view class="tips_popup_btn u-flex">
          <button class="iKnow_btn iKnow_btn1 iKnow_btn_l" hover-class='hover' @click.stop="goCommerceFn()">创作带货</button>
          <button class="iKnow_btn iKnow_btn1" hover-class='hover' open-type="share" @click.stop="
          (1)">邀请帮卖</button>
        </view>
    </view>
  </u-popup>
  <!-- 发布成功弹窗 -->
</PublicPage>
</template>

<script>
import SearchInput from "@/components/searchInput/index.vue";
import PublicPage from "@/components/publicPage/index.vue"
import goodsApi from "@/api/goods.js";
export default {
  components: {SearchInput,PublicPage},
  data() {
    return {
      isIOS: uni.getSystemInfoSync().system.indexOf("Android") !== 0,
      clientParams: {
        currentPage: 1,
        pageSize: 10
      },
      activeData: {id: ''},
      // 侧边栏
      categories: [],
      queryGoodsType: false,
      goodsData: {},
      goodsList: [],
      disabledType: true,
      operationData: {},
      searchName: '',
      isLoadType: true, // 处理onShow是否加载
      releaseType: false, // 发布成功弹窗
      operatorIDArr: [], // 过滤不弹发布商品成功弹窗用户ID白名单'1475460810832752642', '1475457907124482049'
    };
  },
  computed: {
    goodsShareData () {
      return this.$store.state.goodsShareData
    },
    userInfo () {
      return this.$store.state.userInfo
    },
  },
  onLoad() {
    // 隐藏菜单胶囊的分享按钮
    wx.hideShareMenu({
      menus: ["shareAppMessage"]
    })
  },
  onShow () {
    if (!this.isLoadType) {
      this.isLoadType = true
      return
    }
    this.queryCategoryFn()
    this.init()
    this.queryGoodsDetailsFn(this.activeData.id)
    if (!this.activeData.id){
      this.activeData = {
        ...this.activeData,
        id: ''
      }
    }
    // 白名单用户不弹发布成功弹窗
    if (this.goodsShareData.isShare&&!this.operatorIDArr.includes(this.$store.state.userInfo.accountId)) {
      this.releaseType = true
      let shareData = this.goodsShareData // 初始化下isShare不重复弹
      shareData = {
        ...this.goodsShareData,
        isShare: false
      }
      this.$store.commit('GOODS_SHARE_DATA', shareData)
    }
  },
  onShareAppMessage(res) {
    const _shareObj = {
      title: this.goodsShareData.title,
      imageUrl: this.goodsShareData.url,
      path: `pagesB/goods/goodsDetails?shopWindowId=${this.goodsShareData.shopWindowId}&shareType=true&applyForHelp=true&idCode=${this.userInfo.idCode}`
    }
    // 分享参数打印
    console.log(JSON.parse(JSON.stringify({_shareObj})), '分享参数打印')
    return _shareObj
  },
  methods: {
    closeReleaseFn (type) {
      this.releaseType = false
      if (type == 1) {
        this.isLoadType=false // 调用分享不刷新数据
      } else {
        this.$store.commit('GOODS_SHARE_DATA', {}) // 关闭弹窗初始化分享数据
      }
    },
    goCommerceFn () { // 去笔记带货把刚发布的商品带过去
      let selectIdArr = []
      let selectGoodsArr = []
      this.goodsList.forEach((item, i)=>{
        if (item.shopWindowId == this.goodsShareData.shopWindowId) {
          selectGoodsArr.push(item)
          selectIdArr.push(item.id)
        }
      })
      this.$store.commit('SELECT_GOODSID_ARR', selectIdArr)
      this.$store.commit('SELECT_GOODS_ARR', selectGoodsArr)
      this.releaseType = false
      this.$store.commit('GOODS_SHARE_DATA', {}) // 关闭弹窗初始化分享数据
      this.navigateTo({ url: '/pagesA/release/issueEdit?pageType=2' })
    },
    goBackFn () {
      let routeArr = getCurrentPages()
      this.$store.commit('SELECT_GOODSID_ARR', [])
      this.$store.commit('SELECT_GOODS_ARR', [])
      this.$store.commit('SELECTED_SPEC', [])
      if (routeArr&&routeArr.length>=2&&routeArr[routeArr.length-2].route == "pagesA/libraryGoods/addProduct") {
        this.switchTab({url: `/${routeArr[0].route}`})
      } else {
        this.navigateBack({
          delta: 1
        })
      }
    },
    init () {
      this.goodsData = {}
      this.clientParams = {
        currentPage: 1,
        pageSize: 10
      },
      this.queryGoodsType = false
    },
    joinTheWindowFn (item,type,index) {
      let params = {
        spuId: item.id,
        isShopWindow: type
      }
      goodsApi.updateShopWindow(params).then(async (res_) => {
        if (res_.code == 200) {
          this.goodsList[index].isShopWindow = type
          this.$forceUpdate()
          wx.showToast({
            icon: 'none',
            mask: true,
            title: type==1?'移出成功！':'加入成功!'
          })
        }
      })
    },
    goToClassifyFn () {
      this.navigateTo({ url: '/pagesA/libraryGoods/classify' })
    },
    editGoodsFn(data) {
      this.navigateTo({ url: `/pagesA/libraryGoods/addProduct?spuId=${data.id}` })
    },
    goToOpenGroupFn () {
      let url = '/pagesA/release/issueEdit'
      if (this.selectIdArr.length>0) {
        url = '/pagesA/release/issueEdit?openGroupType=1'
      }
      this.navigateTo({ url: url })
    },
    operationFn (data,index) {
      this.operationData = {}
      this.operationData = {...data, index: index}
      let this_ = this
      wx.showModal({
        title: this_.operationData.status==1?'是否下架商品？':'是否上架商品？',
        content: this_.operationData.status==1?'下架后商品将从橱窗移出，不能再被帮卖':'上架后商品将添加到我的橱窗，并且可以被帮卖',
        confirmColor: '#E44435',
        cancelColor: '#969799',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            let params = {
              spuId: this_.operationData.id,
              status: this_.operationData.status==1?'2':'1'
            }
            goodsApi.updateStatus(params).then(async (res_) => {
              if (res_.code == 200) {
                wx.showToast({
                  icon: 'none',
                  mask: true,
                  title: this_.operationData.status==1?'下架成功!':'上架成功!'
                })
                this_.goodsList[this_.operationData.index] = {
                  ...this_.goodsList[this_.operationData.index],
                  status: params.status
                }
                this_.$forceUpdate()
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    deleteFn (data,index) {
      this.operationData = {}
      this.operationData = {...data, index: index}
      let this_ = this
      wx.showModal({
        title: '是否删除该商品？',
        content: '删除后商品将从橱窗移出，不能再被帮卖',
        confirmColor: '#E44435',
        cancelColor: '#969799',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            let params = {
              spuIds: this_.operationData.id
            }
            goodsApi.deleteGoods(params).then(async (res_) => {
              if (res_.code == 200) {
                wx.showToast({
                  icon: 'none',
                  mask: true,
                  title: '删除成功!'
                })
                this_.goodsList.splice(this_.operationData.index, 1)
                this_.$forceUpdate()
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    searchInputFn (e) {
      this.init()
      this.searchName = e
      this.queryGoodsDetailsFn(this.activeData.id)
    },
    queryCategoryFn () {
      goodsApi.getCategoryByAccountId().then(async (res_) => {
        if (res_.code == 200) {
          let categoryArr = res_.data
          categoryArr.unshift({id:'', name: '全部'})
          this.categories = []
          this.categories = [...categoryArr]
        }
      })
    },
    scrolltolowerFn () {
      if (this.queryGoodsType) return
      this.clientParams = {
        ...this.clientParams,
        currentPage: this.clientParams.currentPage+1
      }
      this.queryGoodsDetailsFn(this.activeData.id)
    },
    queryGoodsDetailsFn (id) {
      let params = {
        categoryId: id
      }
      if (this.searchName) {
        params = {
          ...params,
          goodsName: this.searchName
        }
      }
      params = {...params, ...this.clientParams}
      goodsApi.getGoodsDetails(params).then(async (res_) => {
        if (res_.code == 200) {
          this.goodsData = {...res_.data}
          if (this.goodsData.records.length>0) {
            this.goodsData.records.forEach(item => {
              item.images = JSON.parse(item.images)
            })
            this.goodsList = this.clientParams.currentPage>1?this.goodsList.concat(this.goodsData.records):this.goodsData.records
          }
          this.disabledType = this.goodsList.length>0?false:true
          this.queryGoodsType = this.goodsData.records.length<this.clientParams.pageSize?true:false
        }
      })
    },
    //  切换侧边栏
    changeIndex(item) {
      this.activeData = item
      this.searchName = ''
      this.init()
      this.queryGoodsDetailsFn(this.activeData.id)
    },
  },
  filters: {
    statusType (nval) {
      switch (Number(nval)) {
        case 1:
          return "出售中"
        case 2:
          return "未上架"
        default:
          return "--"
      }
    },
  },
  onUnload(){ // 判断用户是否侧滑，数据影响到发布时的页面
    this.$store.commit('SELECT_GOODSID_ARR', [])
    this.$store.commit('SELECT_GOODS_ARR', [])
    this.$store.commit('SELECTED_SPEC', [])
  }
};
</script>

<style lang="scss" scoped>
.category {
  width: 100%;
  height: 100%;
  position: relative;
}
.add_goods_box {
  position: fixed;
  right: 0rpx;
  bottom: 180rpx;
  z-index: 20;
  width: 144rpx;
  height: 144rpx;
  img {
    width: 100%;
    height: 100%;
  }
  &.add_goods_box_ios {
    bottom: 218rpx;
  }
}
.content {
  display: flex;
  flex: 1;
  position: relative;
  height: calc(100% - 200rpx);
}
.manage_sort_box {
  position: absolute;
  bottom: 100rpx;
  left: 0;
  background: #F9F9F9;
  width: 200rpx;
  height: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  color: rgba(0, 0, 0, 0.6);
  &.manage_sort_box_ios {
    bottom: 160rpx;
  }
  img{
    width: 32rpx;
    height: 32rpx;
    margin-right: 8rpx;
  }
}
.goods-left {
  width: 200rpx;
  flex: 0 0 auto;
  height: 100%;
  .li {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    box-sizing: border-box;
    color: rgba(0, 0, 0, 0.6);
    &.active {
      color: #e44435;
      background-color: #fff;
      position: relative;
      &::before {
        position: absolute;
        content: "";
        width: 6rpx;
        height: 100rpx;
        background-color: #e44435;
        left: 0;
      }
    }
  }
  // 隐藏滚动条
  &::-webkit-scrollbar {
    display: none;
  }
}
.cate2 {
  .title {
    height: 110rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #e0e0e0;
    text {
      margin: 0 30rpx;
      color: #000;
    }
  }
  .cate3-wrapper {
    display: flex;
    flex-wrap: wrap;
    .cate3 {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 33.33%;
      margin-bottom: 10rpx;
      image {
        width: 120rpx;
        height: 120rpx;
      }
    }
  }
}

.scroll-view-box {
  background-color: #F2F3F5;
  height: 100%;
}
.not_goods_box {
  width: 100%;
  height: 100%;
  position: relative;
  .not_msg_box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    img {
      width: 320rpx;
      height: 194rpx;
    }
    p {
      width: 320rpx;
      height: 40rpx;
      font-size: 28rpx;
      font-weight: 400;
      text-align: center;
      color: rgba(0,0,0,0.30);
      line-height: 40rpx;
    }
  }
}
// 右侧商品列表
.goods-right {
  padding: 16rpx;
  box-sizing: border-box;
  .goods-right-li {
    margin-bottom: 16rpx;
    background: #fff;
    border-radius: 8rpx;
    box-shadow: 0rpx -2rpx 0rpx 0rpx #eeeeee inset;
  }
  .goods-list {
    display: flex;
    padding: 20rpx;
    border: 2rpx solid #f2f3f5;
    flex: 1;
    .goods-list-img {
      margin: 0 16rpx 0 0rpx;
      .list-img {
        display: block;
        width: 128rpx;
        height: 128rpx;
        // background: #ccc;
        border-radius: 4rpx;
      }
      .status_box {
        display: block;
        margin: 16rpx auto 0;
        width: 96rpx;
        height: 32rpx;
        font-size: 20rpx;
        background-color: #F2F3F5;
        color: #969799;
        text-align: center;
        line-height: 32rpx;
        border-radius: 16rpx;
        &.status_box_at {
          background-color: #E44435;
          color: #fff;
        }
      }
    }
    .goods-list-name {
      font-size: 28rpx;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.9);
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
    .goods-list-sfts,
    .goods-list-inventory {
      font-size: 24rpx;
      margin: 8rpx 0;
      line-height: 32rpx;
    }
    .goods-marketPrice_box {
      font-size: 20rpx;
      color: #969799;
      font-weight: 400;
      line-height: 32rpx;
      text-decoration: line-through;
    }
    .goods-list-price {
      display: flex;
      .now {
        font-size: 28rpx;
        font-weight: 500;
        line-height: 40rpx;
      }
      .past {
        margin-left: 16rpx;
        font-size: 24rpx;
        position: relative;
        font-family: PingFangSC-Regular, PingFang SC;
        p {
          width: 44rpx;
          border: 1rpx solid #000;
          position: absolute;
          top: 40%;
        }
      }
    }
  }
  .goods-list-operation {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx;
    .goods-list-operation_r {
      display: flex;
      align-items: center;
    }
    .btn_box {
      font-size: 24rpx;
      font-weight: 400;
      color: #969799;
      line-height: 32rpx;
      margin-right: 32rpx;
      &:last-child {
        margin-right: 0;
      }
      img {
        width: 32rpx;
        height: 32rpx;
        margin-right: 8rpx;
      }
    }
  }
}
.tips_popup_box {
	width: 622rpx;
  position: relative;
  .close_box {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    color: #969799;
  }
	.tips_popup_title {
		font-size: 32rpx;
    text-align: center;
	}
  .tips_popup_title1 {
    font-size: 36rpx;
    color: #323233;
    font-weight: 600;
    text-align: center;
  }
  .tips_popup_text {
    font-size: 32rpx;
    color: #969799;
    text-align: center;
  }
	.tips_popup_btn {
		border: 2rpx solid #EBEDF0;
		.iKnow_btn {
			width: 100%;
			height: 96rpx;
			font-size: 36rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #E44435;
      &.iKnow_btn1 {
        width: 50%;
      }
      &.iKnow_btn_l {
        color: #969799;
      }
		}
	}
}
</style>
